"""
GGB Generation Conversation API
专门用于对话服务的 FastAPI 应用
"""

import datetime
from fastapi import FastAPI, HTTPException, status
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse, StreamingResponse
import logging

# Import conversation service components
from services.conversation_service_v2 import process_message_stream
from model.http_models import ChatRequest

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)

# Create FastAPI app
app = FastAPI(
    title="GGB Generation Conversation API",
    description="对话式数学问题处理系统，支持几何问题求解和 GeoGebra 可视化",
    version="1.0.0",
    docs_url="/docs",
    redoc_url="/redoc"
)

# 允许跨域请求
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"],
)

# Add conversation service routes
@app.post("/api/v2/chat", tags=["对话"])
async def chat_v2(request: ChatRequest):
    """
    统一的对话接口，支持创建新对话和在现有对话中发送消息
    
    - **user_id**: 用户ID（必需）
    - **message**: 用户消息内容（必需）
    - **conversation_id**: 对话ID（可选，不提供则创建新对话）
    - **title**: 对话标题（可选）
    - **description**: 对话描述（可选）
    - **message_order**: 消息顺序（可选，默认为1）
    
    返回流式响应，包含处理的每个步骤
    """
    try:
        conversation_id = request.conversation_id
        
        # If no conversation_id is provided, create a new conversation
        if not conversation_id:
            # TODO: Implement database operations to create new conversation
            conversation_id = 1  # Placeholder, replace with actual ID from database
            logger.info(f"Creating new conversation for user {request.user_id}")
        else:
            logger.info(f"Using existing conversation {conversation_id} for user {request.user_id}")
        
        # Return streaming response
        return StreamingResponse(
            process_message_stream(
                conversation_id=conversation_id,
                user_message=request.message,
                message_order=request.message_order or 1
            ),
            media_type="text/event-stream",
            headers={
                "Cache-Control": "no-cache",
                "Connection": "keep-alive",
                "X-Accel-Buffering": "no"  # Disable nginx buffering
            }
        )
    except Exception as e:
        logger.error(f"Error in chat endpoint: {str(e)}")
        return JSONResponse(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            content={"detail": f"An error occurred: {str(e)}"}
        )

# Legacy chat endpoint for backward compatibility
@app.post("/chat", tags=["对话"])
async def chat_legacy(request: ChatRequest):
    """向后兼容的对话接口，功能与 /api/v2/chat 相同"""
    return await chat_v2(request)

@app.get("/health", tags=["系统"])
async def health_check():
    """健康检查端点"""
    return {
        "status": "healthy",
        "service": "GGB Generation Conversation API",
        "timestamp": datetime.datetime.now().isoformat(),
        "version": "1.0.0"
    }

@app.get("/", tags=["系统"])
async def root():
    """根端点，返回API信息"""
    return {
        "message": "GGB Generation Conversation API",
        "version": "1.0.0",
        "docs": "/docs",
        "health": "/health",
        "endpoints": {
            "chat_v2": "/api/v2/chat",
            "chat_legacy": "/chat"
        }
    }

if __name__ == "__main__":
    import uvicorn
    
    logger.info("Starting GGB Generation Conversation API...")
    uvicorn.run(
        app, 
        host="0.0.0.0", 
        port=8080,
        log_level="info",
        access_log=True
    ) 